<?php
namespace app\middleware;

use think\facade\Request;

class PermissionCheck
{
    public function handle($request, \Closure $next)
    {
        $user = $request->user;
        $path = $request->pathinfo();
        $method = $request->method();
        
        // 获取用户权限
        $permissions = $this->getUserPermissions($user->user_id);
        
        // 检查是否有权限访问
        if (!$this->checkPermission($permissions, $path, $method)) {
            return json(['code' => 403, 'message' => '无权访问']);
        }
        
        return $next($request);
    }
    
    /**
     * 获取用户权限
     * @param int $userId
     * @return array
     */
    private function getUserPermissions(int $userId): array
    {
        // 这里可以从缓存或数据库获取用户权限
        // 示例代码，实际应根据你的权限系统实现
        return [
            ['path' => 'user/profile', 'method' => 'GET'],
            ['path' => 'user/update', 'method' => 'POST']
        ];
    }
    
    /**
     * 检查权限
     * @param array $permissions
     * @param string $path
     * @param string $method
     * @return bool
     */
    private function checkPermission(array $permissions, string $path, string $method): bool
    {
        foreach ($permissions as $permission) {
            if ($permission['path'] === $path && $permission['method'] === $method) {
                return true;
            }
        }
        return false;
    }
}